import json
import paho.mqtt.client as mqtt
import time

class GPSDataPublisher:
    def __init__(self, broker_host, broker_port=1883):
        self.broker_host = broker_host
        self.broker_port = broker_port
        self.client = mqtt.Client()
        self.topic = "/device1/gps_data"
        
        # 设置回调函数
        self.client.on_connect = self.on_connect
        self.client.on_publish = self.on_publish
        
    def on_connect(self, client, userdata, flags, rc):
        if rc == 0:
            print("成功连接到MQTT broker")
        else:
            print(f"连接失败，错误代码: {rc}")
            
    def on_publish(self, client, userdata, mid):
        print(f"消息发布成功，消息ID: {mid}")
        
    def connect(self):
        try:
            self.client.connect(self.broker_host, self.broker_port, 60)
            self.client.loop_start()
            return True
        except Exception as e:
            print(f"连接异常: {e}")
            return False
            
    def publish_gps_data(self, gps_data):
        """
        发布GPS数据
        :param gps_data: 符合规范的GPS数据字典
        """
        try:
            payload = json.dumps(gps_data)
            result = self.client.publish(self.topic, payload, qos=1)
            
            if result.rc == mqtt.MQTT_ERR_SUCCESS:
                print(f"GPS数据发布成功")
                return True
            else:
                print(f"发布失败，错误代码: {result.rc}")
                return False
                
        except Exception as e:
            print(f"发布异常: {e}")
            return False
            
    def disconnect(self):
        self.client.loop_stop()
        self.client.disconnect()
        print("MQTT连接已断开")

# 使用示例
if __name__ == "__main__":
    publisher = GPSDataPublisher("broker.example.com")
    
    if publisher.connect():
        gps_data = {
            "utc_time": "084530.00",
            "latitude": 31.23045,
            "longitude": 121.47379,
            "satellites": 8,
            "altitude": 25.45,
            "true_north_heading": 45.5,
            "magnetic_north_heading": 46.2,
            "ground_speed_kn": 12.5,
            "ground_speed_kmh": 23.15
        }
        
        publisher.publish_gps_data(gps_data)
        time.sleep(1)
        publisher.disconnect()
